<?php
declare (strict_types = 1);

namespace app\command;

use GuzzleHttp\Client;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

class JinShop extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('sync-shop')
            ->setDescription('the sync-shop command');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);

        //获取商家数据
        $this->getShop();

        // 指令输出
        $output->writeln('sync-shop');
    }

    protected function getShop(){
        //获取店铺
        $shopIds = Db::name('activity_goods')->field('shop_ids,shop_name')->where('shop_ids != ""')->group('shop_ids')->select();

        if($shopIds){
            foreach($shopIds as $k=>$v){
                //获取数据
                $cmm = $this->getCmm($v['shop_name'],$v['shop_ids']);
                //获取评分
                $rate = $this->getRate($v['shop_ids']);
                $sp = $this->getSp($v['shop_ids']);
//                echo '<pre>';print_r($rate);exit;
                $data = [
                    'name' => $v['shop_name'],
                    'shop_logo' => $sp['shop_logo'],
                    'shop_url' => $sp['shop_url'],
                    'letter' => 0, //商家信誉
                    'join_time' => 0, //入驻天数
                    'shop_product' => $rate['shop_product'], //宝贝描述
                    'shop_service' => $rate['shop_service'], //卖家服务
                    'shop_logistics' => $rate['shop_logistics'], //物流描述
                    'cate_attr' => $cmm['cate_attr'], //商家类目
                    'shelves' => $cmm['shelves'], //上架商品数
                    'sale_yes' => $cmm['sale_yes'], //昨日销量
                    'sale_total' => $cmm['sale_total'], //总销量
                    'promotion_num' => $cmm['promotion_num'], //推广达人数
                    'sale_price_yes' => $cmm['sale_price_yes'],//昨日销售额
                    'sale_price' => $cmm['sale_price'], //总销售额
                    'shop_id' => $v['shop_ids'],
                    'shop_tel' => $cmm['shop_tel'],
                ];
                $res = Db::name('shop')->where(['shop_id'=>$v['shop_ids']])->find();
                if(!$res){
                    Db::name('shop')->insert($data);
                }else{
                    Db::name('shop')->where(['shop_id'=>$v['shop_ids']])->update($data);
                }

                echo '.';
                if($k % 100 == 0){
                    sleep(1);
                }
            }
        }
    }

    protected function getCmm($name,$shop_id){
        $url = 'https://api-service.chanmama.com/v1/shop/search';
        $param = [
            'page' => 1,
            'big_category' => '',
            'first_category' => '',
            'keyword' => $name,
            'sort' => 'volume',
            'orderby' => 'desc',
            'size' => 50,
            'has_aweme' => 0,
            'has_live' => 0,
            'avg_price' => '',
            'avg_amount' => '',
            'expr_score' => '',
        ];
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://api-service.chanmama.com/v1/shop/search'
        ];
        $client = new Client();
        try {
            $response = $client->request('GET', $url, ['query'=>$param, 'headers'=>$headers]);
            $result = json_decode($response->getBody()->getContents(), true);
            $d = [
                'shop_logo' => '',
                'shop_url' => '',
                'cate_attr' => '',
                'shelves' => 0,//上架商品数
                'sale_yes' => 0,//昨日销量
                'sale_total' => 0,//总销量
                'promotion_num' => 0,//推广达人数
                'sale_price_yes' => 0,//昨日销售额
                'sale_price' => 0,//总销售额
                'shop_tel' => '',//店铺联系电话
            ];
            if(isset($result['data']['list']) && $result['data']['list']){
                foreach($result['data']['list'] as $k=>$v){
                    if($v['shop_id'] == $shop_id){
                        $d['shop_logo'] = isset($v['shop_icon']) ? $v['shop_icon'] : '';
                        $d['shop_url'] = isset($v['shop_url']) ? $v['shop_url'] : '';
                        $d['cate_attr'] = isset($v['category_arr']) ? json_encode($v['category_arr']) : '';
                        $d['shelves'] = isset($v['total_product_num']) ? $v['total_product_num'] : 0;
                        $d['sale_yes'] = isset($v['volume']) ? $v['volume'] : 0;
//                    $d['sale_total'] = isset($v['total_amount_30']) ? $v['total_amount_30'] : 0;
                        $d['promotion_num'] = isset($v['author_count']) ? $v['author_count'] : 0;
                        $d['sale_price_yes'] = isset($v['amount']) ? $v['amount'] : 0;
                        $d['sale_price'] = isset($v['total_amount_30']) ? $v['total_amount_30'] : 0;
                        $d['shop_tel'] = isset($v['shop_tel']) ? $v['shop_tel'] : '';
                        $d['shop_name'] = $name;
                    }
                }
            }
            return $d;
        }catch (\Exception $e){
            Log::info('调用接口失败,商铺id: '.$shop_id . '=>' . $e->getMessage());
            exit;
        }
    }

    protected function getRate($shop_id){
        $url = 'https://ken.snssdk.com/shop/score';
        $param = [
            'id' => $shop_id,
            'b_type_new' => 0,
            'device_id' => 0,
            'is_outside' => 1,
        ];
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://ken.snssdk.com/shop/score'
        ];
        $client = new Client();
        $response = $client->request('GET', $url, ['query'=>$param, 'timeout'=>180, 'headers'=>$headers]);
        $result = json_decode($response->getBody()->getContents(), true);
        $data = [
            'shop_product' => '',
            'shop_service' => '',
            'shop_logistics' => '',
        ];
        if($result['data']){
            $data['shop_product'] = $result['data']['product'];
            $data['shop_service'] = $result['data']['shop'];
            $data['shop_logistics'] = $result['data']['logistics'];
        }

        return $data;
    }

    protected function getSp($shop_id){
        $url = 'https://ec.snssdk.com/shop/getInfo';
        $param = [
            'id' => $shop_id,
            'b_type_new' => 0,
            'device_id' => 0,
            'is_outside' => 1,
        ];
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://ec.snssdk.com/shop/getInfo'
        ];
        $client = new Client();
        $response = $client->request('GET', $url, ['query'=>$param, 'timeout'=>180, 'headers'=>$headers]);
        $result = json_decode($response->getBody()->getContents(), true);
        $data = [
            'shop_logo' => '',
            'shop_url' => 'https://haohuo.jinritemai.com/views/shop/index?id='.$shop_id,
        ];
        if($result['data']){
            $data['shop_logo'] = $result['data']['shop_logo'];
        }

        return $data;
    }
}
